# import hashlib
# import time
# import requests
# from typing import Dict, Optional

# class EventCompanyClient:
#     """
#     赛事公司HTTP接口客户端
    
#     功能：
#     1. 处理登录认证
#     2. 自动生成请求签名
#     3. 提供基础API调用方法
#     """
    
#     def __init__(self, base_url: str, app_id: str, app_secret: str):
#         """
#         初始化客户端
        
#         :param base_url: 接口基础地址
#         :param app_id: 应用ID
#         :param app_secret: 应用密钥
#         """
#         self.base_url = base_url.rstrip('/')
#         self.app_id = app_id
#         self.app_secret = app_secret
#         self.access_token: Optional[str] = None
#         self.token_expire_time: int = 0
    
#     async def _generate_signature(self, params: Dict) -> str:
#         """
#         生成请求签名
        
#         :param params: 请求参数
#         :return: 签名字符串
#         """
#         # 1. 参数按key排序
#         sorted_params = sorted(params.items(), key=lambda x: x[0])
        
#         # 2. 拼接成key=value格式
#         param_str = '&'.join([f"{k}={v}" for k, v in sorted_params])
        
#         # 3. 拼接app_secret
#         sign_str = f"{param_str}&{self.app_secret}"
        
#         # 4. MD5加密
#         return hashlib.md5(sign_str.encode('utf-8')).hexdigest()
    
#     async def _ensure_token_valid(self):
#         """
#         确保access_token有效
#         """
#         if not self.access_token or time.time() >= self.token_expire_time:
#             await self._login()
    
#     async def _login(self):
#         """
#         登录获取JWT令牌
#         """
#         login_params = {
#             'name': self.app_id,
#             'pw': self.app_secret
#         }
        
#         # 使用x-www-form-urlencoded格式发送登录请求
#         headers = {'Content-Type': 'application/x-www-form-urlencoded'}
#         login_url = f"{self.base_url}/login"
        
#         try:
#             response = requests.post(login_url, data=login_params, headers=headers)
#             response.raise_for_status()
            
#             login_data = response.json()
#             self.access_token = login_data['token']
#             self.token_expire_time = time.time() + 12 * 3600  # 12小时有效期
            
#             # 更新基础URL为登录返回的地址
#             if 'address' in login_data:
#                 self.base_url = f"http://{login_data['address']}"
                
#         except requests.exceptions.RequestException as e:
#             raise Exception(f"登录失败: {str(e)}")
    
#     async def _request(self, endpoint: str, params: Dict = None, method: str = 'GET') -> Dict:
#         """
#         基础请求方法
        
#         :param endpoint: 接口端点
#         :param params: 请求参数
#         :param method: 请求方法
#         :return: 响应数据
#         """
#         await self._ensure_token_valid()
        
#         if params is None:
#             params = {}
            
#         # 添加公共参数
#         params.update({
#             'app_id': self.app_id,
#             'timestamp': int(time.time()),
#             'access_token': self.access_token
#         })
        
#         # 生成签名
#         params['sign'] = await self._generate_signature(params)
        
#         # 发送请求
#         url = f"{self.base_url}{endpoint}"
#         headers = {
#             'Content-Type': 'application/json',
#             'Authorization': f"Bearer {self.access_token}"  # 统一使用Authorization头
#         }
        
#         try:
#             if method.upper() == 'GET':
#                 response = requests.get(url, params=params, headers=headers)
#             else:
#                 response = requests.post(url, json=params, headers=headers)
            
#             response.raise_for_status()
#             return response.json()
#         except requests.exceptions.RequestException as e:
#             if hasattr(e, 'response') and e.response:
#                 error_msg = f"请求失败: {e.response.status_code} - {e.response.text}"
#             else:
#                 error_msg = f"请求失败: {str(e)}"
#             raise Exception(error_msg)
    
#     # 示例API方法
#     # 获取比赛信息
#     async def get_games_list(self) -> list:
#         """
#         获取比赛列表
        
#         :return: 比赛信息列表，包含id、name、createdate和finishdate字段
#         """
#         try:
#             response = await self._request('/games')
#             if isinstance(response, list):
#                 return response
#             return []
#         except Exception as e:
#             print(f"获取比赛列表失败: {str(e)}")
#             return []
            
#     # 获取项目列表
#     async def get_events_list(self, game_id: int) -> list:
#         """
#         获取比赛项目列表
        
#         :param game_id: 比赛ID
#         :return: 项目信息列表，包含id、name、isfinished等字段
#         """
#         try:
#             params = {'gameid': game_id}
#             response = await self._request('/events', params=params)
#             if isinstance(response, list):
#                 return response
#             return []
#         except Exception as e:
#             print(f"获取比赛项目列表失败: {str(e)}")
#             return []
            
#     async def get_event_start_time(self, event_id: int) -> Optional[int]:
#         """
#         获取项目开始时间戳
        
#         :param event_id: 项目ID
#         :return: Linux时间戳（转换后的），获取失败返回None
#         """
#         try:
#             params = {'id': event_id}
#             response = await self._request('/start', params=params, method='GET')
            
#             if isinstance(response, list) and len(response) > 0:
#                 timestamp_str = response[0].get('timestamp')
#                 if timestamp_str:
#                     timestamp = int(timestamp_str)
#                     # 转换公式: linux时间戳=该时间戳/10000-11644473600000
#                     return timestamp // 10000 - 11644473600000
#             return None
#         except Exception as e:
#             print(f"获取项目开始时间失败: {str(e)}")
#             return None
            
#     async def get_checkpoints_list(self, event_id: int) -> list:
#         """
#         获取计时点列表
        
#         :param event_id: 项目ID
#         :return: 计时点信息列表，包含posname、distance、important等字段
#         """
#         try:
#             params = {'id': event_id}
#             response = await self._request('/pos', params=params, method='GET')
            
#             if isinstance(response, list):
#                 return response
#             return []
#         except Exception as e:
#             print(f"获取计时点列表失败: {str(e)}")
#             return []
            
#     async def get_players_list(self, event_id: int) -> list:
#         """
#         获取运动员列表
        
#         :param event_id: 项目ID
#         :return: 运动员信息列表，包含bib、name、groupname、team等字段
#         """
#         try:
#             params = {'id': event_id}
#             response = await self._request('/players', params=params, method='GET')
            
#             if isinstance(response, list):
#                 return response
#             return []
#         except Exception as e:
#             print(f"获取运动员列表失败: {str(e)}")
#             return []
            
#     async def get_detailed_players_list(self, event_id: int) -> list:
#         """
#         获取详细运动员列表
        
#         :param event_id: 项目ID
#         :return: 运动员信息列表，包含bib、name、phone、idnumber等完整字段
#         """
#         try:
#             params = {'id': event_id}
#             response = await self._request('/players/all', params=params, method='GET')
            
#             if isinstance(response, list):
#                 return response
#             return []
#         except Exception as e:
#             print(f"获取详细运动员列表失败: {str(e)}")
#             return []
            
#     async def get_final_results_all(self, event_id: int) -> list:
#         """
#         获取最终全量成绩数据
        
#         :param event_id: 项目ID
#         :return: 运动员最终成绩列表，包含bib、name、finalresult等字段
#         """
#         try:
#             params = {'id': event_id}
#             response = await self._request('/results/final/all', params=params, method='GET')
            
#             if isinstance(response, list):
#                 return response
#             return []
#         except Exception as e:
#             print(f"获取最终成绩数据失败: {str(e)}")
#             return []
            
#     async def get_live_results_all(self, event_id: int) -> Dict:
#         """
#         获取实时全量成绩数据
        
#         :param event_id: 项目ID
#         :return: 包含eventname、pos和players字段的字典，其中results数组索引与计时点顺序严格对应
#         """
#         try:
#             params = {'id': event_id}
#             response = await self._request('/results/all', params=params, method='GET')
            
#             if isinstance(response, dict):
#                 return response
#             return {}
#         except Exception as e:
#             print(f"获取实时成绩数据失败: {str(e)}")
#             return {}
            
#     async def get_single_player_result(self, event_id: int, bib: str) -> Optional[Dict]:
#         """
#         获取单个运动员最终成绩数据
        
#         :param event_id: 项目ID
#         :param bib: 运动员号码
#         :return: 运动员成绩字典，包含bib、name、finalresult等字段，失败返回None
#         """
#         try:
#             params = {'id': event_id, 'bib': bib}
#             response = await self._request('/results/final/single', params=params, method='GET')
            
#             if isinstance(response, dict):
#                 return response
#             return None
#         except Exception as e:
#             print(f"获取运动员{bib}成绩数据失败: {str(e)}")
#             return None
            
#     # 获取简略全量成绩数据
#     async def get_base_results_all(self, event_id: int) -> list:
#         """
#         获取简略全量成绩数据
        
#         :param event_id: 项目ID
#         :return: 运动员基本成绩列表，包含bib、foul和results字段，其中results数组索引与计时点顺序严格对应
#         """
#         try:
#             params = {'id': event_id}
#             response = await self._request('/results/all/base', params=params, method='GET')
            
#             if isinstance(response, list):
#                 return response
#             return []
#         except Exception as e:
#             print(f"获取简略成绩数据失败: {str(e)}")
#             return []
            
#     async def get_incremental_results(self, event_id: int, timestamp: int) -> Dict:
#         """
#         获取实时增量成绩数据
        
#         :param event_id: 项目ID
#         :param timestamp: 时间戳(第一次请求传0，之后传上次返回的timestamp)
#         :return: 包含players和timestamp的字典，players数组包含变化的运动员成绩信息
#         """
#         try:
#             params = {'id': event_id, 'timestamp': timestamp}
#             response = await self._request('/results/all/base/inc', params=params, method='GET')
            
#             if isinstance(response, dict):
#                 return response
#             return {}
#         except Exception as e:
#             print(f"获取增量成绩数据失败: {str(e)}")
#             return {}
            
#     async def get_live_single_player_result(self, event_id: int, bib: str) -> Optional[Dict]:
#         """
#         获取单个运动员实时成绩数据
        
#         :param event_id: 项目ID
#         :param bib: 运动员号码
#         :return: 运动员实时成绩字典，包含bib、name、results等字段，其中results数组包含实时分段成绩信息
#         """
#         try:
#             params = {'id': event_id, 'bib': bib}
#             response = await self._request('/results/single', params=params, method='GET')
            
#             if isinstance(response, dict):
#                 return response
#             return None
#         except Exception as e:
#             print(f"获取运动员{bib}实时成绩数据失败: {str(e)}")
#             return None
            
#     async def get_base_single_player_result(self, event_id: int, bib: str) -> Optional[Dict]:
#         """
#         获取单个运动员基本简略数据
        
#         :param event_id: 项目ID
#         :param bib: 运动员号码
#         :return: 包含bib、foul和results字段的字典，其中results数组包含成绩信息
#         """
#         try:
#             params = {'id': event_id, 'bib': bib}
#             response = await self._request('/results/single/base', params=params, method='GET')
            
#             if isinstance(response, dict):
#                 return response
#             return None
#         except Exception as e:
#             print(f"获取运动员{bib}基本简略数据失败: {str(e)}")
#             return None
            
#     async def get_results_by_positions(self, event_id: int, bib: str = "", positions: list = None) -> Dict:
#         """
#         根据计时点位置获取成绩数据
        
#         :param event_id: 项目ID
#         :param bib: 运动员号码(可选)
#         :param positions: 计时点位置列表
#         :return: 包含成绩数据的字典
#         """
#         try:
#             if positions is None:
#                 positions = []
                
#             payload = {
#                 'id': event_id,
#                 'bib': bib,
#                 'pos': positions
#             }
            
#             headers = {
#                 'Authorization': 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX3RlbmFudF9rZXkiOiJrZCIsImxvZ2luX3VzZXJfa2V5IjoiMmFmZjQ0MDMtNmU3Ny00ZTVkLWE2OTctZjNmZTAyN2E5NWM4In0.CejAhLxn-eWyGdcI0cXjQiIsMJbkTrkiGkrTI5naLKK6osFB4RVCKpINlyNb9A4cKGBAJnPZyPySkqjt1qrD9w',
#                 'Content-Type': 'application/json'
#             }
#             url = f"{self.base_url}/prod-api/tp-api/results"
#             response = requests.post(url, json=payload, headers=headers).json()
            
#             if isinstance(response, dict):
#                 return response
#             return {}
#         except Exception as e:
#             print(f"获取计时点成绩数据失败: {str(e)}")
#             return {}

# # 使用示例
# client = EventCompanyClient(
#     base_url="https://api.example.com",
#     app_id="your_app_id",
#     app_secret="your_app_secret"
# )
# await client.login()
# event_info = await client.get_event_info("event123")
# print(event_info)

# ret = await get_results_by_positions(6, "", [0, 1, 99])
# print(ret)